<template>
  <div class="page-wrapper">
    <c-card title="项目列表" class="com-wrapper">
      <el-button slot="func" type="primary" size="small" class="item" @click="showAddDlg">添加</el-button>
      <div class="search-row">
        <c-search
          v-model="searchText"
          :height="30"
          :width="200"
          placeholder="公司名称搜索"
          class="item"
          @submit="_getComList"
        />
      </div>
      <el-table ref="table" v-loading="loading" :data="comList" stripe style="width: 100%">
        <el-table-column prop="name" label="公司名称"></el-table-column>
        <el-table-column prop="regionName" label="行政区域"></el-table-column>
        <el-table-column prop="phoneNum" label="联系电话"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button size="small" type="text" @click="showEditDlg(row)">编辑</el-button>
            <el-button size="small" type="text" @click="deleteCom(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page.sync="page.index"
          :total="page.total"
          @current-change="_getComList"
        ></el-pagination>
      </div>
    </c-card>
    <c-dlg
      v-if="comInfo"
      :title="(comInfo.pkid ? '编辑' : '添加') + '公司'"
      :visible.sync="dialogVisible"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="comInfo"
        label-width="60px"
        class="demo-ruleForm"
        label-position="top"
        style="width: 100%;"
      >
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="公司名称" prop="name">
              <el-input v-model="comInfo.name" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="公司全称" prop="fullName">
              <el-input v-model="comInfo.fullName" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="公司简介" prop="details">
              <el-input v-model="comInfo.details" type="textarea" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="行政区域" prop="gvarID">
              <!-- <el-input v-model="comInfo.gvarID" size="small"></el-input> -->
              <el-select v-model="comInfo.gvarID" size="small" placeholder="请选择">
                <el-option v-for="g in gvars" :key="g.areaNo" :label="g.name" :value="g.areaNo"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="联系电话" prop="phoneNum">
              <el-input v-model="comInfo.phoneNum" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="用电户号" prop="clientNumber">
              <el-input v-model="comInfo.clientNumber" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="用电容量" prop="loadcapacity">
              <el-input v-model="comInfo.loadcapacity" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="变压器数量" prop="transformercount">
              <el-input v-model="comInfo.transformercount" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="公司坐标" prop="location">
              <el-input :value="comInfo.location" size="small" @click.native="loadMap">
                <i slot="suffix" class="el-input__icon el-icon-position"></i>
              </el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="父级单位" prop="parentId">
              <el-select v-model="comInfo.parentId" clearable size="small">
                <el-option v-for="c in comList1" :key="c.pkid" :label="c.name" :value="c.pkid"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="客户联系人" prop="leader">
              <el-input v-model="comInfo.leader" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row last-row">
          <div class="row-item">
            <el-form-item label="地址" prop="address">
              <el-input v-model="comInfo.address" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button size="small" type="danger" @click="submitForm">提交</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </c-dlg>
    <c-dlg :visible.sync="mapVisible" :type="2" title="选择坐标" no-padding>
      <el-select
        v-model="address"
        :loading="loading1"
        :remote-method="searchPos"
        filterable
        remote
        size="small"
        class="pos-input"
        placeholder="输入地址"
        @change="getPoint"
      >
        <el-option v-for="(s, i) in sugestions" :key="i" :label="s" :value="s"></el-option>
      </el-select>
      <div id="map-container"></div>
    </c-dlg>
  </div>
</template>

<script>
import CCard from "@/components/CCard";
import CSearch from "@/components/CSearch";
import CDlg from "@/components/CDlg";
import { elIsPhone } from "@/utils/validate";
import { calcPageNum } from "@/utils";
import { editCom, deleteCom } from "@/api/user";
let map = null,
  maker = null;
const BMap = window.BMap;
export default {
  name: 'CompanyList',
  components: {
    CCard,
    CSearch,
    CDlg
  },
  data() {
    return {
      searchText: "",
      loading: false,
      loading1: false,
      comList: [],
      dialogVisible: false,
      comInfo: null,
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      rules: {
        name: [{ required: true, message: "该字段不能为空", trigger: "blur" }],
        fullName: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        details: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        gvarID: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        phoneNum: [
          { required: true, message: "该字段不能为空", trigger: "blur" },
          { validator: elIsPhone, trigger: "blur" }
        ],
        clientNumber: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        loadcapacity: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        transformercount: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        location: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        leader: [{ required: true, message: "该字段不能为空", trigger: "blur" }]
      },
      gvars: null,
      mapVisible: false,
      address: "",
      sugestions: [],
      comList1: ''
    };
  },
  mounted() {
    const h = this.$refs["table"].$el.clientHeight;
    const n = calcPageNum(h);
    this.$set(this.page, "size", n);
    this._getComList();
    this._getGvars();
    // this.comList1 = this.$store.getters.comList
    this.comLis()
  },
  methods: {
    comLis() {
      const arr = this.$store.getters.comList
      arr.unshift({
        name: '0',
        pkid: 0
      })
      this.comList1 = arr
    },
    isDisplay(e) {
      console.log(e)
    },
    _getComList() {
      const name = this.searchText;
      const params = {
        pageNo: this.page.index,
        pageSize: this.page.size
      };
      name && (params.name = name);
      this.loading = true;
      return this.$axios
        .get("/plat/sys/client/list", { params })
        .then(res => {
          if (res.code === 1) {
            this.$set(this.page, "total", res.data.total);
            this.comList = res.data.rows;
          } else throw res.msg;
        })
        .catch(e => this.$message.error(e))
        .finally(() => (this.loading = false));
    },
    _getGvars() {
      return this.$axios
        .get("plat/sys/common/govareat/dropDownList")
        .then(res => {
          if (res.code === 1) {
            this.gvars = res.data;
          }
        })
        .catch(e => {});
    },
    showAddDlg() {
      if (!this.comInfo) {
        this.comInfo = {};
      }
      if (this.comInfo && this.comInfo.pkid) {
        this.comInfo = {};
      }
      this.dialogVisible = true;
    },
    showEditDlg(row) {
      console.log("comInfo", row)
      if (this.comInfo && this.comInfo.pkid === row.pkid) {
        this.dialogVisible = true;
      } else {
        this.comInfo = {
          createTime: row.createTime,
          updateTime: row.updateTime,
          status: row.status,
          pkid: row.pkid,
          // gvarID: row.regionName,
          gvarID: row.gvarID,
          unitNo: row.unitNo,
          name: row.name,
          fullName: row.fullName,
          address: row.address,
          leader: row.leader,
          phoneNum: row.phoneNum,
          capacity: row.capacity,
          parentId: row.parentId,
          type: row.type,
          clientNumber: row.clientNumber,
          oldUuid: row.oldUuid,
          logo: row.logo,
          location: row.location,
          jointime: row.jointime,
          expirationtime: row.expirationtime,
          roomcount: row.roomcount,
          transformercount: row.transformercount,
          loadcapacity: row.loadcapacity,
          sort: row.sort,
          conExeTime: row.conExeTime,
          details: row.details
        }
        // this.comInfo = row;
        this.dialogVisible = true;
      }
    },
    deleteCom(row) {
      this.$confirm("此操作将永久删除该公司, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return deleteCom(row.pkid).then(() => {
          this._getComList();
          // this.$store.dispatch("user/getComList");
        });
      });
    },
    loadMap() {
      this.mapVisible = true;
      this.$nextTick(async () => {
        const that = this;
        const p = [106.504108, 29.598395];
        map = new BMap.Map("map-container");
        const point = new BMap.Point(p[0], p[1]);
        map.centerAndZoom(point, 14);
        map.setCurrentCity("重庆");
        map.enableScrollWheelZoom(true);
        map.addEventListener("click", that.pointSelect);
        const geolocation = new BMap.Geolocation();
        if (this.comInfo.location) {
          const pa = this.comInfo.location.split(",");
          const mp = new BMap.Point(pa[0], pa[1]);
          maker = new BMap.Marker(mp);
          map.addOverlay(maker);
          map.panTo(mp);
          this.showInfoWnd(mp);
        } else {
          geolocation.getCurrentPosition(
            function(r) {
              if (this.getStatus() === window.BMAP_STATUS_SUCCESS) {
                maker = new BMap.Marker(r.point);
                map.addOverlay(maker);
                map.panTo(r.point);
                that.showInfoWnd(r.point);
              } else {
                that.$message.error("定位失败, 请手动选择位置!");
              }
            },
            { enableHighAccuracy: true }
          );
        }
      });
    },
    pointSelect(e) {
      const point = e.point;
      maker = new BMap.Marker(point);
      map.clearOverlays();
      map.addOverlay(maker);
      map.panTo(point);
      this.$nextTick(() => {
        this.showInfoWnd(point);
      });
    },
    showInfoWnd(point) {
      var myGeo = new BMap.Geocoder();
      // 根据坐标得到地址描述
      this.$set(this.comInfo, "location", point.lng + "," + point.lat);
      myGeo.getLocation(point, result => {
        if (result) {
          let title, address;
          const p = result.surroundingPois[0];
          if (!p) {
            title = " ";
            address = result.address;
          } else {
            title = p.title;
            address = p.address;
          }
          var opts = {
            width: 200, // 信息窗口宽度
            height: 100, // 信息窗口高度
            title: title // 信息窗口标题
          };
          var infoWindow = new BMap.InfoWindow("地址：" + address, opts);
          map.openInfoWindow(infoWindow, point);
          this.$set(this.comInfo, "address", address);
        }
      });
    },
    searchPos(v) {
      const that = this;
      const options = {
        onSearchComplete: function(results) {
          if (local.getStatus() === window.BMAP_STATUS_SUCCESS) {
            // 判断状态是否正确
            var s = [];
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              s.push(
                results.getPoi(i).title + " - " + results.getPoi(i).address
              );
            }
            that.sugestions = s;
          }
        }
      };
      var local = new BMap.LocalSearch(map, options);
      local.search(v);
    },
    getPoint(address) {
      var myGeo = new BMap.Geocoder();
      // 将地址解析结果显示在地图上，并调整地图视野
      myGeo.getPoint(
        address,
        point => {
          if (point) {
            map.clearOverlays();
            map.addOverlay(new BMap.Marker(point));
            map.panTo(point);
            this.showInfoWnd(point);
          }
        },
        "重庆市"
      );
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const load = this.$loading();
          return editCom(this.comInfo)
            .then(() => {
              this.dialogVisible = false;
              this.comInfo = null;
              this._getComList();
              // this.$store.dispatch("user/getComList");
              this.$message.success("保持成功");
            })
            .catch(e => this.$message.error(e))
            .finally(() => load.close());
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
#map-container {
  height: 500px;
  width: 1000px;
}
.pos-input {
  position: absolute;
  top: 10px;
  left: 20px;
  width: 300px;
  z-index: 99;
}
</style>
